package utils

import (
	"fmt"
	"net"
)

type UdpLog struct {
	Conn *net.UDPConn
	Addr string
}

//启动一个gw服务的入口
func NewUDPClient() *UdpLog {
	this := &UdpLog{
		Conn: new(net.UDPConn),
		Addr: "127.0.0.1:6666",
	}
	return this
}
func (this *UdpLog) UDPClient() {
	netAddr, err := net.ResolveUDPAddr("udp", this.Addr)
	if err != nil {
		fmt.Println(fmt.Sprintf("error resolving tcp address: %s, ERROR:%s", netAddr, err.Error()))
		return
	} else if err != nil {
		fmt.Println(fmt.Sprintf("error resolving tcp address: %s, ERROR:%s", "netAddr", err.Error()))
		return
	}
	conn, err := net.DialUDP("udp", nil, netAddr)
	if err != nil {
		fmt.Println(fmt.Sprintf("error connect to server@%s ERROR: %s", netAddr, err.Error()))
		return
	} else if err != nil {
		fmt.Println(fmt.Sprintf("error connect to server@%s ERROR: %s", netAddr, err.Error()))
		return
	}
	this.Conn = conn
}

func (this *UdpLog) HandleLog(writelog string) {

	_, err := this.Conn.Write([]byte(writelog))
	if err != nil {
		fmt.Println(fmt.Sprintf("error udp写入数据ERROR: %s --- %s", err.Error(), writelog))
		return
	}
	return
}
